package com.zjdiepu.www.manage.api.base;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.ibiz.base.IBaseAccountBusiUnitService;
import com.zjdiepu.www.model.base.dto.BaseAccountBusiUnit;
import com.zjdiepu.www.model.base.ext.BaseAccountBusiUnitExt;
import com.zjdiepu.www.model.base.request.UnitTreeRequest;
import com.zjdiepu.www.model.system.vo.BaseBusiUnitVo;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * Controller层<br/>
 * @author zhangzhengjian<br/>
 * @time 2017年05月31日 09时36分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "BaseAccountBusiUnitController", produces="application/json;charset=UTF-8")
@Api(tags = {""}, produces="application/json;charset=UTF-8")
public class BaseAccountBusiUnitController extends BaseController {
    @Resource
    private IBaseAccountBusiUnitService baseAccountBusiUnitService;

    /**
     * @author zhangzhengjian <br/>
     * @Title: save  <br/>
     * @Description: 新增 <br/>
     * @param baseAccountBusiUnit
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute BaseAccountBusiUnit baseAccountBusiUnit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	baseAccountBusiUnit.setCreator(currentUser.getId());
    	baseAccountBusiUnit.setCreatorName(currentUser.getName());
    	baseAccountBusiUnit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseAccountBusiUnit.setModifierName(currentUser.getName());
        baseAccountBusiUnitService.saveUpdateAndDelete(baseAccountBusiUnit, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: remove  <br/>
     * @Description: 删除<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseAccountBusiUnitService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: disable  <br/>
     * @Description: 禁用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseAccountBusiUnitService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: enable <br/>
     * @Description: 启用<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	baseAccountBusiUnitService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: modify  <br/>
     * @Description: 修改 <br/>
     * @param baseAccountBusiUnit
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute BaseAccountBusiUnit baseAccountBusiUnit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	baseAccountBusiUnit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	baseAccountBusiUnit.setModifierName(currentUser.getName());
    	baseAccountBusiUnitService.saveUpdateAndDelete(baseAccountBusiUnit, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author zhangzhengjian <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询", response = BaseAccountBusiUnit.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       BaseAccountBusiUnit baseAccountBusiUnit = baseAccountBusiUnitService.selectById(id);
       if(null == baseAccountBusiUnit) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(baseAccountBusiUnit);
    }
    
    /**
     * @author zhangzhengjian <br/>
     * @Title: list  <br/>
     * @Description: 条件查询 <br/>
     * @param baseAccountBusiUnitExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询",response = BaseAccountBusiUnit.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute BaseAccountBusiUnitExt baseAccountBusiUnitExt){
        baseAccountBusiUnitExt.notDeleted();
        PageVo page = getPage(baseAccountBusiUnitExt);
        int records = baseAccountBusiUnitService.countByExt(baseAccountBusiUnitExt);
        page.setRecords(records);
        if (records > 0) {
            List<BaseAccountBusiUnit> dpBaseDataDictionaries = baseAccountBusiUnitService.selectByExt(baseAccountBusiUnitExt);
            page.setRows(dpBaseDataDictionaries);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    /**
     * 业务单位选择树形结构
     * @author xiongxiaotun <br/>
     * @Title mulitList  <br/>
     * @Description 业务单位选择树形结构 <br/>
     * @param unitTreeRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询",response = BaseBusiUnitVo.class, httpMethod="POST")
    @RequestMapping(value = "mulitList", method = RequestMethod.POST)
    public ApiResponse mulitList(@Validated @ModelAttribute UnitTreeRequest unitTreeRequest){
    	getCurrentUser();
    	List<BaseBusiUnitVo> baseBusiUnitVos = baseAccountBusiUnitService.selectMulitList(unitTreeRequest.getScene());
    	//用户已有业务范围
    	String userId = unitTreeRequest.getUserId();
    	if(StringUtils.isNotBlank(userId)) {
    		BaseAccountBusiUnitExt baseAccountBusiUnitExt = new BaseAccountBusiUnitExt();
    		baseAccountBusiUnitExt.setBaseWhere();
    		baseAccountBusiUnitExt.withOutPage();
    		baseAccountBusiUnitExt.setUserId(userId);
    		List<BaseAccountBusiUnit> baseAccountBusiUnits = baseAccountBusiUnitService.selectByExt(baseAccountBusiUnitExt);
    		Set<String> idUnits = baseAccountBusiUnits.stream().map(item -> item.getIdUnit()).collect(Collectors.toSet());
    		for(BaseBusiUnitVo baseBusiUnitVo : baseBusiUnitVos) {
    			String salersmanOrUnitId = baseBusiUnitVo.getId();
    			if(StringUtils.isEmpty(salersmanOrUnitId)) {
    				continue;
    			}
    			if(idUnits.contains(salersmanOrUnitId)) {
    				baseBusiUnitVo.setChecked(true);
    			}
    		}
    	}
    	//关联的业务员账号
    	String salersmanId = unitTreeRequest.getSalersmanId();
    	if(StringUtils.isNotBlank(salersmanId)) {
    		for(BaseBusiUnitVo baseBusiUnitVo : baseBusiUnitVos) {
    			String salersmanOrUnitId = baseBusiUnitVo.getId();
    			if(StringUtils.isEmpty(salersmanOrUnitId)) {
    				continue;
    			}
    			if(salersmanId.equals(salersmanOrUnitId)) {
    				baseBusiUnitVo.setChecked(true);
    				openParent(baseBusiUnitVos, baseBusiUnitVo);
    				break;
    			}
    		}
    	}
        
    	PageVo page = new PageVo();
        if(baseBusiUnitVos==null || baseBusiUnitVos.size()==0){
        	baseBusiUnitVos=CollectionInitUtil.emptyList();
        }
        page.setRows(baseBusiUnitVos);
        return ApiResponse.success(page);
    }
    
    /*
     * 打开父级
     */
    private void openParent(List<BaseBusiUnitVo> baseBusiUnitVos, BaseBusiUnitVo currentBaseBusiUnitVo) {
    	if(CollectionUtils.isEmpty(baseBusiUnitVos)) {
    		return;
    	}
    	if(null == currentBaseBusiUnitVo) {
    		return;
    	}
    	String parentCode = currentBaseBusiUnitVo.getParentCode();
    	if(StringUtils.isBlank(parentCode)) {
    		return;
    	}
    	for(BaseBusiUnitVo baseBusiUnitVo : baseBusiUnitVos) {
    		if(parentCode.equals(baseBusiUnitVo.getOrgCode())) {
    			baseBusiUnitVo.setOpen(true);
    			openParent(baseBusiUnitVos, baseBusiUnitVo);
    			break;
    		}
    	}
     }
    
    @ApiOperation(value = "新增", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "insertBatch", method = RequestMethod.POST)
    public ApiResponse insertBatch(String userId,String codeUnit,String idUnit,@RequestParam(defaultValue="0") Boolean salersman){
    	AbstractSysUser currentUser = getCurrentUser();
    	if(StringUtils.isBlank(userId)) {
            ExceptionHelper.thow("999", "用户ID不能为空");
          } 
        BaseAccountBusiUnitExt baseAccountBusiUnitExt = new BaseAccountBusiUnitExt();
        baseAccountBusiUnitExt.setUserId(userId);
        baseAccountBusiUnitService.deleteByExt(baseAccountBusiUnitExt);
    	List<BaseAccountBusiUnit> list=new ArrayList<BaseAccountBusiUnit>();
    	BaseAccountBusiUnit baseAccountBusiUnit=null;
    	if(idUnit!=null &&idUnit.contains(",")){
    		String[] idUnits=idUnit.split(",");
    		String[] codeUnits=codeUnit.split(",");
    		for (int i = 0; i < idUnits.length; i++) {
    			baseAccountBusiUnit=new BaseAccountBusiUnit();
    			baseAccountBusiUnit.setIdUnit(idUnits[i]);
    			baseAccountBusiUnit.setCodeUnit(codeUnits[i]);
    			baseAccountBusiUnit.setUserId(userId);
    			baseAccountBusiUnit.initInsertData(currentUser.getId(), currentUser.getName());
        		list.add(baseAccountBusiUnit);
			}
    		baseAccountBusiUnitService.insertBatch(list);
    	}else{
    		baseAccountBusiUnit=new BaseAccountBusiUnit();
    		baseAccountBusiUnit.setIdUnit(idUnit);
			baseAccountBusiUnit.setCodeUnit(codeUnit);
			baseAccountBusiUnit.setUserId(userId);
    		baseAccountBusiUnit.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    		baseAccountBusiUnit.setModifierName(currentUser.getName());
    		baseAccountBusiUnitService.saveUpdateAndDelete(baseAccountBusiUnit, OperateType.add);
    	}
    	
    	return ApiResponse.success(true);
    }
}
